package com.isyscore.os.metadata.utils;

import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.metadata.enums.DataSourceTypeEnum;
import com.isyscore.os.metadata.model.entity.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.isyscore.os.core.exception.ErrorCode.DATA_SOURCE_CONNECTION_ERROR;

/**
 * @author fjZheng
 * @version 1.0
 * @date 2020/10/21 16:29
 */
@Slf4j
public final class DbUtils {

    private static Map<String, javax.sql.DataSource> dataSourceMap = new ConcurrentHashMap<>();

    private static javax.sql.DataSource getDataSource(DataSource info) {
        if (null == info) {
            return null;
        }
        if (dataSourceMap.containsKey(info.getName())) {
            return dataSourceMap.get(info.getName());
        }
        HikariDataSource ds = new HikariDataSource();
        DataSourceTypeEnum type = DataSourceTypeEnum.getType(info.getType());
        ds.setDriverClassName(type.getDriverClass());
        ds.setUsername(info.getUserName());
        ds.setPassword(info.getPassword());
        ds.setJdbcUrl(String.format(type.getUrl(), info.getIp(), info.getPort(), info.getDatabaseName()));
        ds.setMaximumPoolSize(5);
        ds.setIdleTimeout(30000);
        dataSourceMap.put(info.getName(), ds);
        return ds;
    }

    /**
     * 获取连接
     *
     * @param datasourceInfo
     * @return
     */
    public static Connection getConn(DataSource datasourceInfo) {
        try {
            javax.sql.DataSource dataSource = getDataSource(datasourceInfo);
            if (null == dataSource) {
                return null;
            }
            return dataSource.getConnection();
        } catch (SQLException e) {
            log.error("获取数据库连接失败：{}", e);
            throw new DataFactoryException(DATA_SOURCE_CONNECTION_ERROR);
        }
    }

    /**
     * 关闭连接
     *
     * @param conn
     * @param ps
     * @param rs
     * @Author tangjiyang
     */
    public static void close(Connection conn, Statement ps, ResultSet rs) {
        org.apache.commons.dbutils.DbUtils.closeQuietly(conn, ps, rs);
    }
}